package com.juc.cyclicbarrier.cyclicbarrier4;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class MyService {
       /**
        * 借助CyclicBarrier类具有计数重置性实现多赛段的比赛实验
        */
	
		/**
		 * 此实验说明CyclicBarrier的parties值 从1 到2 ，然后再恢复到0的过程，证明CyclicBarrier类的
		 * 屏障点是可以复用的.
		 * 其实线程ABCD每到达一个屏障点时的组合有可能是随机的，有可能A和B到达第一屏障，而到达第二屏障
		 * 时的组合却是A和D，因为线程A和D的sleep(long)值较小，也就是sleep(long)用时最少的互相组合，
		 * 继续向下一屏障行进。
		 */
	 private CyclicBarrier cbRef;
	 public MyService(CyclicBarrier cbRef){
		 super(); 
		 this.cbRef = cbRef;
	 }
	 
	 public void beginRun() {
		
		 try {
			long sleepValue = (int)(Math.random() * 10000);
			Thread.sleep(sleepValue);
			System.out.println(Thread.currentThread().getName() + " " + System.currentTimeMillis() + " begin跑第1阶段"   +" "
					+ (cbRef.getNumberWaiting() +1 ) );
			cbRef.await();
			System.out.println(Thread.currentThread().getName() + " " + System.currentTimeMillis() + " end跑第1阶段" +" "  
					+ (cbRef.getNumberWaiting() ) );
			sleepValue = (int)(Math.random() * 10000);
			Thread.sleep(sleepValue);
			System.out.println(Thread.currentThread().getName() + " " + System.currentTimeMillis() + " begin跑第2阶段"   +" "
					+ (cbRef.getNumberWaiting() +1 ) );
			cbRef.await();
			System.out.println(Thread.currentThread().getName() + " " + System.currentTimeMillis() + " end跑第2阶段" +" "  
					+ (cbRef.getNumberWaiting() ) );
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (BrokenBarrierException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	 }
}
